import { defineStore } from 'pinia'
import axios from 'axios'

// 添加请求拦截器，记录所有请求
axios.interceptors.request.use(
    config => {
        console.log('发送请求:', config.method.toUpperCase(), config.url, config.data || '')
        return config
    },
    error => {
        console.error('请求错误:', error)
        return Promise.reject(error)
    }
)

// 添加响应拦截器，记录所有响应
axios.interceptors.response.use(
    response => {
        console.log('收到响应:', response.status, response.config.url, response.data)
        return response
    },
    error => {
        console.error('响应错误:', error.message)
        if (error.response) {
            console.error('错误详情:', error.response.status, error.response.data)
        }
        return Promise.reject(error)
    }
)

export const useScheduleStore = defineStore('schedule', {
    state: () => ({
        employees: [],
        shifts: [],
        schedules: [],
        products: [],
        loading: false,
        error: null
    }),
    
    actions: {
        // 员工相关操作
        async fetchEmployees() {
            this.loading = true
            try {
                console.log('开始获取员工数据...')
                const response = await axios.get('/api/employees')
                console.log('获取员工数据成功:', response.data)
                this.employees = response.data
            } catch (error) {
                console.error('获取员工数据失败:', error)
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async createEmployee(employee) {
            this.loading = true
            try {
                const response = await axios.post('/api/employees', employee)
                this.employees.push(response.data)
                return response.data
            } catch (error) {
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async updateEmployee(employee) {
            this.loading = true
            try {
                console.log('更新员工:', employee)
                const response = await axios.put(`/api/employees/${employee.ID}`, employee)
                const index = this.employees.findIndex(e => e.ID === employee.ID)
                if (index !== -1) {
                    this.employees[index] = response.data
                }
                return response.data
            } catch (error) {
                console.error('更新员工API错误:', error)
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async deleteEmployee(id) {
            this.loading = true
            try {
                console.log('删除员工ID:', id)
                await axios.delete(`/api/employees/${id}`)
                this.employees = this.employees.filter(e => e.ID !== id)
            } catch (error) {
                console.error('删除员工API错误:', error)
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        // 班次相关操作
        async fetchShifts() {
            this.loading = true
            try {
                const response = await axios.get('/api/shifts')
                this.shifts = response.data
            } catch (error) {
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async createShift(shift) {
            this.loading = true
            try {
                const response = await axios.post('/api/shifts', shift)
                this.shifts.push(response.data)
                return response.data
            } catch (error) {
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async updateShift(shift) {
            this.loading = true
            try {
                console.log('更新班次:', shift)
                const response = await axios.put(`/api/shifts/${shift.ID}`, shift)
                const index = this.shifts.findIndex(s => s.ID === shift.ID)
                if (index !== -1) {
                    this.shifts[index] = response.data
                }
                return response.data
            } catch (error) {
                console.error('更新班次API错误:', error)
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async deleteShift(id) {
            this.loading = true
            try {
                console.log('删除班次ID:', id)
                await axios.delete(`/api/shifts/${id}`)
                this.shifts = this.shifts.filter(s => s.ID !== id)
            } catch (error) {
                console.error('删除班次API错误:', error)
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        // 排班相关操作
        async fetchSchedules() {
            this.loading = true
            try {
                const response = await axios.get('/api/schedules')
                this.schedules = response.data
            } catch (error) {
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async createSchedule(schedule) {
            this.loading = true
            try {
                const response = await axios.post('/api/schedules', schedule)
                this.schedules.push(response.data)
                return response.data
            } catch (error) {
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async updateSchedule(schedule) {
            this.loading = true
            try {
                console.log('更新排班:', schedule)
                const response = await axios.put(`/api/schedules/${schedule.ID}`, schedule)
                const index = this.schedules.findIndex(s => s.ID === schedule.ID)
                if (index !== -1) {
                    this.schedules[index] = response.data
                }
                return response.data
            } catch (error) {
                console.error('更新排班API错误:', error)
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async deleteSchedule(id) {
            this.loading = true
            try {
                console.log('删除排班ID:', id)
                await axios.delete(`/api/schedules/${id}`)
                this.schedules = this.schedules.filter(s => s.ID !== id)
            } catch (error) {
                console.error('删除排班API错误:', error)
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async batchDeleteSchedules(ids) {
            this.loading = true
            try {
                console.log('批量删除排班IDs:', ids)
                const deletePromises = ids.map(id => axios.delete(`/api/schedules/${id}`))
                await Promise.all(deletePromises)
                this.schedules = this.schedules.filter(s => !ids.includes(s.ID))
                return ids.length
            } catch (error) {
                console.error('批量删除排班API错误:', error)
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },
        
        // 产品相关操作
        async fetchProducts() {
            this.loading = true
            try {
                const response = await axios.get('/api/products')
                this.products = response.data
            } catch (error) {
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async createProduct(product) {
            this.loading = true
            try {
                const response = await axios.post('/api/products', product)
                this.products.push(response.data)
                return response.data
            } catch (error) {
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async updateProduct(product) {
            this.loading = true
            try {
                console.log('更新产品:', product)
                const response = await axios.put(`/api/products/${product.ID}`, product)
                const index = this.products.findIndex(p => p.ID === product.ID)
                if (index !== -1) {
                    this.products[index] = response.data
                }
                return response.data
            } catch (error) {
                console.error('更新产品API错误:', error)
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        },

        async deleteProduct(id) {
            this.loading = true
            try {
                console.log('删除产品ID:', id)
                await axios.delete(`/api/products/${id}`)
                this.products = this.products.filter(p => p.ID !== id)
            } catch (error) {
                console.error('删除产品API错误:', error)
                this.error = error
                throw error
            } finally {
                this.loading = false
            }
        }
    }
}) 